"""
用户账户相关功能，注册，短信，登录，注销
"""
import datetime
import uuid

from django.db.models import Q
from utils.encrypt import md5
from utils.img_code import check_code
from web import models
from django.http import JsonResponse
from django_redis import get_redis_connection
from django.shortcuts import render, HttpResponse,redirect
from web.form.acount import RegisterModelForm,LoginPwdForm,LoginMsgForm,SmsForm




def sms_to(request):
    """ 发送短信（加手机号验证） """
    form = SmsForm(request,data=request.GET)
    # if (type == "register" and not tel_obj) or (type == "login" and tel_obj): # 需满足当注册时手机号不存在，登陆时手机号存在才允许发短信
    #     if template_id:
    #         code = random.randrange(1000, 9999)
    #         res = send_sms_single(tel, template_id, [code, ])
    #         if res["result"] == 0:
    #             conn = get_redis_connection()
    #             conn.set(tel, code, ex=60)  # ex=设置时长
    #             return JsonResponse({"status": True, "msg": "发送成功"})
    #         return JsonResponse({"status": False, "msg": res["errmsg"]})
    #     return JsonResponse({"status": False, "msg": '找不到模板'})
    # return JsonResponse({"status": False, "msg": '手机号不满足当前要求'})
    # 将上面的繁琐判断全放进钩子函数
    if form.is_valid():
        return JsonResponse({"status":True})
    return JsonResponse({"status":False,"msg":form.errors})


def register(request):
    """ 注册 """
    if request.method == "GET":
        form = RegisterModelForm()
        return render(request, "register.html", {"form": form, "title": "注册"})
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # instance = form.save() 在数据库新增一条数据，并将新增的这条数据赋值给instance
        instance = form.save() # 注册成功在user表新增一条记录
        # 创建一条交易记录
        policy_object = models.PricePolicy.objects.filter(category=1,title="个人免费版").first()
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()), # 随机生产字符串方法
            user = instance, # 外键可以直接传obj
            price_policy=policy_object,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()
        )
        return JsonResponse({"status":True,"msg":"/paslogin/"})
    return JsonResponse({"status": False, "msg": form.errors})

# 密码登录
def login(request):
    if request.method =="GET":
        form = LoginPwdForm(request)
        return render(request,'login.html',{"form":form,"title":"登录"})
    form = LoginPwdForm(request,data=request.POST)
    if form.is_valid():# 当每个字段数据都符合规定
        # form验证验证码，当验证码验证通过再判断账户密码
        user = request.POST.get("username")
        pwd = md5(request.POST.get("password"))
        user_obj = models.UserInfo.objects.filter(Q(username=user) | Q(email=user)).filter(password=pwd).first()
        # user_obj1 = models.UserInfo.objects.filter(**{"username":user,"password":pwd}).first()
        # user_obj2 = models.UserInfo.objects.filter(**{"email":user,"password":pwd}).first()
        if user_obj:
            request.session['user'] =  {"username":user_obj.username,"id":user_obj.id}
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect("/index")
        form.add_error("password", "用户名或密码错误")
        return render(request, 'login.html', {'form': form,"title":"登录"})
    return render(request, 'login.html', {'form': form,"title":"登录"})

# 短信登录
def msg_login(request):
    if request.method =="GET":
        form = LoginMsgForm
        return render(request,'msg_login.html',{"form":form,"title":"登录"})
    form = LoginMsgForm(data=request.POST)
    if form.is_valid():
       user_obj = models.UserInfo.objects.filter(mobile_phone=form.cleaned_data["mobile_phone"]).first()
       request.session['user'] = {"username":user_obj.username,"id":user_obj.id}
       request.session.set_expiry(60 * 60 * 24 * 14)
       return JsonResponse({"status":True,"msg":"/index/"})
    return JsonResponse({"status":False,"msg":form.errors})

def img_code(request):
    """生成图片验证码"""
    img,code_str = check_code()#使用封装好的验证码类
    request.session['img_code'] = code_str # 将验证码存入session,用于登录取出校验
    request.session.set_expiry(60) # 设置session时间为60秒，用于验证码60秒失效
    # 3. 将图片写入内存(Python3)
    from io import BytesIO
    stream = BytesIO()
    img.save(stream, 'png')#这里是将图片存入stream对象，stream.getvalue()是获取stream里存的图片
    return HttpResponse(stream.getvalue())

def index(request):

    return render(request,'index.html')

def logout(request):
    print("走了logout")
    request.session.clear()
    return redirect('/index/')